<?php
use DTOs\RSSReaderResult;
/**
 * @author jrodriguez
 * @copyright 2013
 */
 require_once $rootPath.'Gazzetta.DAL/Repositories/RSSItemRepository.php';
 require_once $rootPath.'Gazzetta.DAL/Repositories/RSSSourceRepository.php'; 
 require_once $rootPath.'Gazzetta.BL/RSSParser.php';
 require_once $rootPath.'Gazzetta.BL/DTOs/RSSReaderResult.php';
 require_once $rootPath.'Gazzetta.Entities/RSSItem.php';
 require_once $rootPath.'Gazzetta.Utils/StringBuilder.php';
class RSSReader
{
	protected $_rssSourceRepository;
	function __construct()
	{
		$this->_rssSourceRepository = new RSSSourceRepository();
	}
	
	public function parseRssSource(RSSSource $rsssource)
	{
		 $result = new RSSReaderResult();
		 $repository = new RSSItemRepository();
		 
		 $parser = new RSSParser($rsssource->getLink());
		 
		 $nn = $parser->getNumberOfNews();
		 
		 $result->setLink($rsssource->getLink());
		 $result->setProcessed($nn);
		 
		 $added = 0;
		 for($i=0;$i<$nn;$i++)
		 {
			 $tempLink = $parser->getItemLink($i);
			if (!$repository->exists($tempLink))
			{
				$rssItem = new RSSItem();
				
				$rssItem->setIdRSSSource($rsssource->getId());
                $stringHelper = new StringBuilder($parser->getItemDescription($i));
				$rssItem->setDescription($stringHelper->replace("'",""));
				$rssItem->setLink($parser->getItemLink($i));
                $stringHelper->set($parser->getItemTitle($i));
				$rssItem->setTitle($stringHelper->replace("'",""));
				$rssItem->setImageLink($parser->getItemImage($i));
                $rssItem->setPubDate($parser->getItemPubdate($i));
                
				$repository->add($rssItem);
				$added++;
			}
		 }	
		 $result->setAdded($added);
		 //$result->setTotal($repository->getAmountBySourceId($rsssource->getId()));
		 return $result;
		
	}
	
	public function processRSSs()
	{
		$rssResults = array();
		
		$activeSources = $this->_rssSourceRepository->getActiveRssSources();
		
		
		foreach ($activeSources as $source)
		{			 
			 $rssResults[] = $this->parseRssSource($source);
		}
		return $rssResults;
	}
	
	private function log($message)
	{
		echo ' Logging -' . $message;
	}
}

?>